package cn.edu.niit.alienlab.jshttplessonserver.apis;

import cn.edu.niit.alienlab.jshttplessonserver.domain.*;
import cn.edu.niit.alienlab.jshttplessonserver.dto.CategoryDto;
import cn.edu.niit.alienlab.jshttplessonserver.dto.MovieInfoDto;
import cn.edu.niit.alienlab.jshttplessonserver.dto.YearDto;
import cn.edu.niit.alienlab.jshttplessonserver.service.ActorInfoService;
import cn.edu.niit.alienlab.jshttplessonserver.service.MovieRatingsService;
import cn.edu.niit.alienlab.jshttplessonserver.service.MovieService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/movies")
@CrossOrigin(origins = "*")
public class MovieResource {
    @Autowired
    private MovieService movieService;

    @Autowired
    private ActorInfoService actorInfoService;
    @Autowired
    private MovieRatingsService movieRatingsService;

    @Value("${application.file.diskpath}")
    String diskPath;
    @Value("${application.file.fileurl}")
    String fileUrl;


    @GetMapping("/categories")
    public List<CategoryDto> allCategory() {
        return movieService.findAllCategory();
    }

    @GetMapping("/years")
    public List<YearDto> allYear() {
        return movieService.findAllYear();
    }

    @GetMapping(value = "/movie-list")
    public Page<MovieInfoDto> findMovieInfo(
                @RequestParam(required = false) String keyword,
                @RequestParam(required = false) Integer movie_year,
                @RequestParam(required = false) String[] categories,
                @RequestParam(defaultValue = "0",required = false) Integer pageNum,
                @RequestParam(defaultValue = "10",required = false) Integer pageSize) {

        return movieService.findMovie(keyword, movie_year, categories, pageNum, pageSize);
    }

    /**
     * API4:按影片id查询影片详细信息，包含导演、编剧、出品公司详细信息
     * @param movie_id
     * @return
     */
    @GetMapping("/detail/{movie_id}")
    public ResponseEntity getMovieByMovieID(@PathVariable Integer movie_id){
        List<MovieInfo> list=movieService.findMovieByMovieID(movie_id);
        if(list!=null && list.size()>0){
            return ResponseEntity.ok(list.get(0));
        }else{
            return ResponseEntity.badRequest().body("未找到id为"+movie_id+"的影片信息");
        }

    }

    /**
     * API5：按影片id获取影片演员列表
     * @param movie_id
     * @return
     */
    @GetMapping("/actors/{movie_id}")
    public ResponseEntity getActorInfoByMovieId(@PathVariable Integer movie_id) {
        List<ActorInfo> list = new ArrayList<>();
        list = actorInfoService.selectActorInfoByMovieId(movie_id);
        return ResponseEntity.ok(list);
    }


    /**
     * API6:按影片id获取影片评价明细，返回评价列表
     * @param movie_id
     * @return
     */
    @GetMapping("/ratings/{movie_id}")
    public ResponseEntity getRatingsByMovieId(@PathVariable Integer movie_id) {
        List<MovieRatings> list = new ArrayList<>();
        list = movieRatingsService.selectRatingsByMovieId(movie_id);
        return ResponseEntity.ok(list);
    }

    @GetMapping("/directors")
    public ResponseEntity allDirectors(@RequestParam(required = false,defaultValue = "") String keyword){
        List<DirectorInfo> result=this.movieService.getAllDirectors(keyword);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/admin/create")
    public ResponseEntity addMovie(@RequestBody String movieJson,HttpServletRequest request){
        String authorization=request.getHeader("Authorization");
        if(authorization==null) {
            return ResponseEntity.status(401).body("用户未登录");
        }
        try {
            JSONObject movieJsonObject= JSONObject.parseObject(movieJson);
            MovieInfo paramMovie=new MovieInfo();
            paramMovie.setMovieId(movieJsonObject.getInteger("movieId"));
            if(paramMovie.getMovieId()==null){
                return ResponseEntity.badRequest().body("未指定影片id");
            }
            paramMovie.setMovieYear(movieJsonObject.getInteger("movieYear"));
            paramMovie.setMoviePublishDate(movieJsonObject.getString("moviePublishDate"));
            paramMovie.setImg(movieJsonObject.getString("img"));
            paramMovie.setLength(movieJsonObject.getInteger("length"));
            paramMovie.setDirectorInfo(movieJsonObject.getObject("directorInfo",DirectorInfo.class));
            if(paramMovie.getDirectorInfo()==null || paramMovie.getDirectorInfo().getDirectorId()==null){
                return ResponseEntity.badRequest().body("未指定影片导演或缺少导演id");
            }
            paramMovie.setNameEn(movieJsonObject.getString("nameEn"));
            paramMovie.setName(movieJsonObject.getString("name"));
            paramMovie.setRating(movieJsonObject.getFloat("rating"));
            paramMovie.setPersonCount(movieJsonObject.getInteger("personCount"));
            paramMovie.setRatingCount(movieJsonObject.getInteger("ratingCount"));
            paramMovie.setTitleOthers(movieJsonObject.getString("title_others"));
            paramMovie.setStory(movieJsonObject.getString("story"));
            paramMovie.setTypeInfoList(movieJsonObject.getJSONArray("typeInfoList").toJavaList(TypeInfo.class));
            if(paramMovie.getTypeInfoList()==null || paramMovie.getTypeInfoList().size()==0){
                return ResponseEntity.badRequest().body("未指定影片分类");
            }
            MovieInfo result=movieService.createMovie(paramMovie);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PutMapping("/admin/update")
    public ResponseEntity updateMovie(@RequestBody String movieJson,HttpServletRequest request){
        String authorization=request.getHeader("Authorization");
        if(authorization==null) {
            return ResponseEntity.status(401).body("用户未登录");
        }
        try {
            JSONObject movieJsonObject= JSONObject.parseObject(movieJson);
            MovieInfo paramMovie=new MovieInfo();
            paramMovie.setMovieId(movieJsonObject.getInteger("movieId"));
            if(paramMovie.getMovieId()==null){
                return ResponseEntity.badRequest().body("未指定影片id");
            }
            paramMovie.setMovieYear(movieJsonObject.getInteger("movieYear"));
            paramMovie.setMoviePublishDate(movieJsonObject.getString("moviePublishDate"));
            paramMovie.setImg(movieJsonObject.getString("img"));
            paramMovie.setLength(movieJsonObject.getInteger("length"));
            paramMovie.setDirectorInfo(movieJsonObject.getObject("directorInfo",DirectorInfo.class));
            if(paramMovie.getDirectorInfo()==null || paramMovie.getDirectorInfo().getDirectorId()==null){
                return ResponseEntity.badRequest().body("未指定影片导演或缺少导演id");
            }
            paramMovie.setNameEn(movieJsonObject.getString("nameEn"));
            paramMovie.setName(movieJsonObject.getString("name"));
            paramMovie.setPersonCount(movieJsonObject.getInteger("personCount"));
            paramMovie.setRatingCount(movieJsonObject.getInteger("ratingCount"));
            paramMovie.setTitleOthers(movieJsonObject.getString("title_others"));
            paramMovie.setStory(movieJsonObject.getString("story"));
            paramMovie.setTypeInfoList(movieJsonObject.getJSONArray("typeInfoList").toJavaList(TypeInfo.class));
            if(paramMovie.getTypeInfoList()==null || paramMovie.getTypeInfoList().size()==0){
                return ResponseEntity.badRequest().body("未指定影片分类");
            }
            MovieInfo result=movieService.updateMovie(paramMovie);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/admin/upload")
    public ResponseEntity updateHeadImage(MultipartFile imageFile, HttpServletRequest request){
        String authorization=request.getHeader("Authorization");
        if(authorization==null) {
            return ResponseEntity.status(401).body("用户未登录");
        }
        if(imageFile==null){
            return ResponseEntity.badRequest().body("请上传头像图片");
        }
        //1、获得文件名
        String fileName=imageFile.getOriginalFilename();
        //2、解析后缀名，最后一个.后面的内容
        String extName=fileName.substring(fileName.lastIndexOf("."));
        //3、使用uuid生成一个新的文件名，加上解析出的后缀名，用于在服务器上存储文件时的名称。
        String serverFileName= UUID.randomUUID().toString()+extName;
        //4、使用新文件名，在配置好的文件夹中，创建空白文件
        String serverDiskPath=diskPath+serverFileName;
        File serverFile=new File(serverDiskPath);
        //5、将接收到的文件写入新建的空白文件
        try {
            imageFile.transferTo(serverFile);
        //6、通过新文件名，生成url访问地址
            String serverFileUrl=fileUrl+"/"+serverFileName;
            return ResponseEntity.ok(serverFileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("文件传输出错");
        }
    }


    @DeleteMapping("/admin/delete/{movieId}")
    public ResponseEntity deleteMovie(@PathVariable Integer movieId){
        boolean result=this.movieService.deleteMovie(movieId);
        return ResponseEntity.ok(result);
    }

}
